package com.tea.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tea.utils.JwtUtils;
import com.tea.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import static java.util.Collections.emptyList;

// JWT认证过滤器
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final JwtUtils jwtUtils;
    private final List<String> whiteList;
    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    
    // 构造函数注入依赖
    public JwtAuthenticationFilter(JwtUtils jwtUtils, List<String> whiteList) {
        this.jwtUtils = jwtUtils;
        this.whiteList = whiteList;
        // 打印出实际注入的白名单列表
        log.info("🔐 JwtAuthenticationFilter初始化完成, 白名单路径数量: {}, 详情: {}", whiteList.size(), whiteList);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        log.info("🌐 收到请求: {}", requestURI);

        // 检查是否是白名单中的路径
        if (isWhiteListed(requestURI)) {
            chain.doFilter(request, response);
            return;
        }

        String token = getTokenFromHeader(request);
        try {
            if (token != null && jwtUtils.validateToken(token)) {
                String openid = jwtUtils.getOpenidFromToken(token);
                UsernamePasswordAuthenticationToken auth =
                        new UsernamePasswordAuthenticationToken(openid, null, emptyList());
                SecurityContextHolder.getContext().setAuthentication(auth);
            } else {
                throw new RuntimeException("无效的Token或未提供Token");
            }
        } catch (Exception e) {
            log.error("认证失败: {}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            Result<String> errorResult = Result.error(401,"无效的Token或未提供Token");
            out.write(new ObjectMapper().writeValueAsString(errorResult));
            out.flush();
            out.close();
            return;
        }
        chain.doFilter(request, response);
    }

    private String getTokenFromHeader(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (StringUtils.hasText(header) && header.startsWith("Bearer ")) {
            return header.substring(7);
        }
        return null;
    }
    
    private boolean isWhiteListed(String requestURI) {
        // 使用AntPathMatcher进行路径匹配，支持通配符
        for (String pattern : whiteList) {
            if (pathMatcher.match(pattern, requestURI)) {
                return true;
            }
        }
        log.info("❌ 路径 {} 不在白名单中，需要JWT认证", requestURI);
        return false;
    }
}